package com.snap.awesomeserial.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;

import com.snap.awesomeserial.AppConfig;
import com.snap.awesomeserial.R;
import com.snap.awesomeserial.framework.MoleExecutor;
import com.snap.awesomeserial.ui.widget.IconButton;

import java.text.SimpleDateFormat;
import java.util.Locale;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity extends AppCompatActivity {

    private Unbinder unbinder;

    private boolean mReceiverTag = false;   //广播注册标识
    private BroadcastReceiver systemTimeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            refreshSystemTime();
        }
    };
    private SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd  HH:mm", Locale.CHINA);
    private CheckBox lightBtn;

    private void refreshSystemTime() {
//        if (timeText != null) {
//            timeText.setText(format.format(new Date()));
//        }
    }

    private void registerSystemTimeBoardCast() {
        IntentFilter timeFilter = new IntentFilter();
        timeFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(systemTimeReceiver, timeFilter);
        mReceiverTag = true;
        refreshSystemTime();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (lightBtn != null) {
            lightBtn.setChecked(AppConfig.Dynamic.light);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layoutResId());
        unbinder = ButterKnife.bind(this);
        IconButton backBtn = findViewById(R.id.back_btn);
        if (backBtn != null) {
            backBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }

        lightBtn = findViewById(R.id.light_btn);
        if (lightBtn != null) {
            lightBtn.setChecked(AppConfig.Dynamic.light);
            lightBtn.setOnCheckedChangeListener((buttonView, isChecked) -> AppConfig.Dynamic.light = isChecked);
        }

//        if (findViewById(R.id.setting_iv) != null) {
//            findViewById(R.id.setting_iv).setOnClickListener(new OnDebounceClickListener() {
//                @Override
//                public void doClick(View v) {
//                    Intent intent = new Intent(BaseActivity.this, SettingActivity.class);
//                    startActivity(intent);
//                }
//            });
//        }
//        timeText = findViewById(R.id.time_text);
//        if (timeText != null) registerSystemTimeBoardCast();
//
//        machineNameTv = findViewById(R.id.machine_name_tv);
//        if (machineNameTv != null) machineNameTv.setText(BuildConfig.FLAVOR);
    }

    protected abstract int layoutResId();

    @Override
    protected void onDestroy() {
        MoleExecutor.getInstance().clear();
        unbinder.unbind();
        if (systemTimeReceiver != null && mReceiverTag) {
            unregisterReceiver(systemTimeReceiver);
        }
        super.onDestroy();
    }

    public void onBack(View view) {
        finishAfterTransition();
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                v.clearFocus();
                hideSoftInput(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

}
